package com.yugao.fintech.draper.security.config;

import com.yugao.fintech.draper.auth.api.SocialFeignApi;
import com.yugao.fintech.draper.security.config.properties.GiteeProperties;
import com.yugao.fintech.draper.security.handler.DefaultGiteeRegisteredClientRepository;
import com.yugao.fintech.draper.security.handler.GiteeRegisteredClientRepository;
import com.yugao.fintech.draper.security.filter.GiteeCodeHttpFilter;
import com.yugao.fintech.draper.security.filter.GiteeAuthorizeHttpFilter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;

/**
 * gitee oauth2 client相关拦截器
 */
@EnableConfigurationProperties(GiteeProperties.class)
@Configuration
public class SocialOAuth2ClientConfigure {

	@Bean
	public DefaultGiteeRegisteredClientRepository giteeRegisteredClientRepository(GiteeProperties giteeProperties,
			StringRedisTemplate redisTemplate, SocialFeignApi socialFeignApi) {
		return new DefaultGiteeRegisteredClientRepository(giteeProperties, redisTemplate, socialFeignApi);
	}

	@Bean
	public FilterRegistrationBean<GiteeAuthorizeHttpFilter> giteeAuthorizeHttpFilterFilterRegistrationBean(
			GiteeRegisteredClientRepository giteeRegisteredClientRepository,
			OAuth2AuthorizationService authorizationService) {
		FilterRegistrationBean<GiteeAuthorizeHttpFilter> registration = new FilterRegistrationBean<>();
		GiteeAuthorizeHttpFilter giteeAuthorizeHttpFilter = new GiteeAuthorizeHttpFilter(
				giteeRegisteredClientRepository, authorizationService);
		registration.setFilter(giteeAuthorizeHttpFilter);
		registration.addUrlPatterns("/gitee/authorize/*");
		return registration;
	}

	@Bean
	public FilterRegistrationBean<GiteeCodeHttpFilter> giteeCodeHttpFilterFilterRegistrationBean(
			GiteeRegisteredClientRepository giteeRegisteredClientRepository) {
		FilterRegistrationBean<GiteeCodeHttpFilter> registration = new FilterRegistrationBean<>();
		registration.setFilter(new GiteeCodeHttpFilter(giteeRegisteredClientRepository));
		registration.addUrlPatterns("/gitee/code/*");
		return registration;
	}
}
